package controller

import (
	"gin/common"
	"gin/response"
	"gin/service"
	"gin/validate"
	"github.com/gin-gonic/gin"
)

func WordSpeechSelect(ctx *gin.Context) {
	var selectDictQuery validate.SelectWordSpeechQuery

	err := ctx.ShouldBindJSON(&selectDictQuery)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	selectQueryParam := common.GenerateSelectQueryParam(selectDictQuery.Param, "log")

	total, resData, queryErr := service.SelectWordSpeech(selectQueryParam)

	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": gin.H{"total": total, "rows": resData}}, "success")
	}
}

// 查询单条词库
func WordSpeechFind(ctx *gin.Context) {
	var selectDictQuery validate.SelectWordSpeechQuery

	err := ctx.ShouldBindJSON(&selectDictQuery)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	selectQueryParam := common.GenerateSelectQueryParam(selectDictQuery.Param, "log")

	resData, queryErr := service.FindWordSpeech(selectQueryParam)

	if queryErr != nil {
		// 查询失败
		response.Fail(ctx, nil, queryErr.Error())
	} else {
		// 查询成功
		response.Success(ctx, gin.H{"data": resData}, "success")
	}
}

// 插入日志
func WordSpeechCreate(ctx *gin.Context) {
	var addWordSpeech validate.AddWordSpeechWrapper

	err := ctx.ShouldBindJSON(&addWordSpeech)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, createErr := service.CreateWordSpeech(addWordSpeech.Data)
	if createErr != nil {
		// 插入失败
		response.Fail(ctx, nil, createErr.Error())
		return
	} else {
		// 插入数据成功
		addWordSpeech.Data.Id = resData.Id
		addWordSpeech.Data.Created = resData.Created
		addWordSpeech.Data.Updated = resData.Updated
	}

	response.Success(ctx, gin.H{"data": addWordSpeech.Data}, "success")
}

func WordSpeechUpdate(ctx *gin.Context) {
	var updateWordSpeech validate.UpdateWordSpeechWrapper

	err := ctx.ShouldBindJSON(&updateWordSpeech)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	resData, createErr := service.UpdateWordSpeech(updateWordSpeech.Data)
	if createErr != nil {
		// 插入失败
		response.Fail(ctx, nil, createErr.Error())
		return
	}

	response.Success(ctx, gin.H{"data": resData}, "success")
}

func WordSpeechDelete(ctx *gin.Context) {
	var deleteWordSpeechParam validate.DeleteWordSpeechParam

	err := ctx.ShouldBindJSON(&deleteWordSpeechParam)

	if err != nil {
		response.Fail(ctx, nil, err.Error())
		return
	}

	selectQueryParam := common.GenerateFilterParam(&deleteWordSpeechParam.Param, "word_speech")

	service.DeleteWordSpeech(&selectQueryParam)

	// 查询成功
	response.Success(ctx, nil, "success")

}
